using System;
using System.Collections.Generic;
using System.Text;
using SharksHunter.Domain.Model;

namespace SharksHunter.Controller.Business.Engine.CSV
{
    class CSVScanner:Interfaces.IScanner<Shot, string>
    {
        public IEnumerable<Shot> Scan(string where)
        {
            long size,crc;
            string name = "", shot = "", prevshot = "";
            Shot newshot = null;
            Item newitem = null;

            string[] stritems = where.Split('\n', '\r');
            foreach(string stritem in stritems)
            {
                if(stritem == "")
                    continue;//because of '\n', '\r' we get empty lines
                string[] fields = stritem.Split(',');
                name = fields[0];
                size = long.Parse(fields[1]);
                crc = long.Parse(fields[2],System.Globalization.NumberStyles.HexNumber);

                newitem = new Item();
                newitem.Name = name;
                newitem.Size = size;
                newitem.CRC32 = crc;

                if (fields.Length >= 4)
                {
                    prevshot = shot;
                    shot = "";
                    for(int i = 3; i < fields.Length ;++i) 
                    {
                        if(fields[i] == "")
                            continue;//ignore empty fields
                        shot += fields[i].ToString() + ",";
                    }
                    if(shot.EndsWith(","))
                        shot = shot.Substring(0, shot.Length-1);

                    if(prevshot != shot)//new shot
                    {
                        newshot = new Shot();
                        newshot.Name = shot;
                        yield return newshot; 
                    }
                    if(newshot!= null)
                        newshot.Items.Add(newitem);
                }
            }
        }
    }
}
